from google.appengine.ext import webapp
from DataClass.FullPage import FullPage
from google.appengine.api import users
from google.appengine.ext.webapp import template
from AdminBase import AdminBase
from DataClass.WebsiteRec import WebsiteRec
from google.appengine.ext import db

import os
import cgi

class EditPageHandler(AdminBase):
    def GetTemplateFileName(self):
        return 'Pages/editpage.html'
        
    def GetBreadcrumbList(self):
        Website = WebsiteRec.GetCurrentWebsite(self.request)
        return [['main', 'admin'],['pages', 'editpages'],['editpage']]
    
    def GetTemplateValuesDict(self, template_values, user):
        retval = template_values

        querystring=cgi.FieldStorage()
        Website = template_values['currentwebsite']
                                  
        pagename=querystring.getvalue('pagename')
    
        Page = FullPage.GetPageBySiteNameAndPageName(Website.sitename, pagename)

        if Page:
            retval['pagename'] = pagename
            retval['content'] = Page.contenttext
            retval['titletext'] = 'Edit Page'
            retval['buttontext'] = 'Update'
            retval['is_update'] = True
        else:
            retval['pagename'] = ""
            retval['content'] = ""
            retval['titletext'] = 'Create New Page'
            retval['buttontext'] = 'Create'
            retval['is_update'] = False

        return retval

    def DoPost(self, user):
        sitename = self.request.get('sitename')
        prevpagename = self.request.get('prevpagename')
        pagename = self.request.get('pagename')
        content = self.request.get('content')
        isnew = self.request.get('isnew') == "isnew"
        Page = None

        if not isnew:
            Page = FullPage.GetPageBySiteNameAndPageName(sitename, prevpagename)
        
        if not Page:
            Page = FullPage()
            Page.sitename = sitename
            Page.authoremail = user.email()

        Page.pagename = pagename
        Page.contenttext = db.Text(content)
        Page.put()
        self.redirect('/editpages')
